import 'package:dio/dio.dart';
import 'package:razer_one/app/main/constants/url_constants.dart';
import 'package:razer_one/app/main/model/http_model.dart';
import 'package:razer_one/app/main/utils/alert_utils.dart';

enum HttpType {
  post,
  get,
  upload,
}

class HttpManager {
  static const String baseURL = kBaseURL;
  static const int timeout = 10000; //超时时间
  static final BaseOptions baseOptions =
      BaseOptions(baseUrl: baseURL, connectTimeout: timeout, headers: {
    "APP-ID": "123456",
  });
  static final Dio dio = Dio(baseOptions);

  static Future<HttpModel> request<T>(
    String url, {
    HttpType httpType = HttpType.post,
    dynamic params,
    bool isShowAlert = true,
  }) async {
    try {
      print("开始请求");

      Response response;
      switch (httpType) {
        case HttpType.get:
          response = await dio.get(url, queryParameters: params);
          break;
        case HttpType.post:
          response = await dio.post(url, data: params);
          break;
        case HttpType.upload:
          params = FormData.fromMap(params);
          response = await dio.post(url, data: params);
          break;
      }

      print("请求成功:请求头是${baseOptions.headers}\n}");
      print("\n参数是$params,url是$url,\n数据是${response.data}\n");

      print(response.data);
      //设置请求头
      HttpModel model = HttpModel.fromJson(response.data);
      model.iSsuccess = true;
      if (!model.iSsuccess) {
        if (isShowAlert == true) AlertUtils.show(model.msg);
      }
      //token失效,跳转登录页面
      if (model.code == "111") {
        // AppRoutesName.navigatorKey.currentState?.pushNamedAndRemoveUntil(
        //     AppRoutesName.meLoginRoute, (route) => false);
      }

      return model;
    } on DioError catch (e) {
      print("请求失败\nurl是$url,参数是$params,\n错误是$e");

      if (e.type == DioErrorType.connectTimeout ||
          e.type == DioErrorType.sendTimeout ||
          e.type == DioErrorType.receiveTimeout) {
        if (isShowAlert == true) AlertUtils.show("请求超时,请稍后再试!");
        HttpModel model = HttpModel();
        return model;
      }
      HttpModel model = HttpModel();
      AlertUtils.show("服务器异常2,请稍后再试");

      return model;
    }
  }
}
